package com.ziyun.pop.mall.module.time.task;

import com.utility.DateUtils;
import com.ziyun.pop.mall.base.utils.SerializeUtil;
import com.ziyun.pop.mall.module.time.action.UserActionTake;
import com.ziyun.pop.mall.module.time.service.PopUserActionService;
import com.ziyun.pop.mall.module.user.entity.PopUserAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentMap;

/**
 * @Author:chenxiaoyi
 * @Date:2018/11/6 16:59
 */
@Component
public class UserActionTask {

    private static Logger _log = LoggerFactory.getLogger(UserActionTask.class);

    private  UserActionTake userActionContext = UserActionTake.getInstance();

    @Autowired
    PopUserActionService popUserActionService;


    @Scheduled(cron = "0 0 0 * * ?") //每天零点执行 用户记录信息
    public void executeUserActionTask() {
        _log.info("开始执行用户行为记录定时任务 [{}] ", DateUtils.formatDefault());
        byte[] bytes = null;
        ConcurrentMap<String, PopUserAction> userActionMap = userActionContext.getUserActionMap();
        try {
            userActionContext.getLock().writeLock().lock();
        	if(!userActionMap.isEmpty()){
        		bytes = SerializeUtil.serializeToString(userActionMap);
        		userActionMap.clear();
        	}
        }finally {
            userActionContext.getLock().writeLock().unlock();
        }

        if(bytes!=null){
            try {
                popUserActionService.insertUserAction(bytes);
            }catch (Exception e){
                _log.error("用户行为记录失败",e);
            }
        }else{
            _log.info("记录为空 结束执行用户行为记录定时任务 [{}] ", DateUtils.formatDefault());
        }
        
    }

}
